package Pet.Management.service.impl;

import Pet.Management.domain.entity.Captcha;
import Pet.Management.repository.CaptchaRepository;
import Pet.Management.service.CaptchaService;
import Pet.Management.utils.CaptchaUtils;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private CaptchaRepository captchaRepository;

    @Autowired
    private Producer captchaProducer;

    @Override
    @Transactional
    public void setCaptchaCode(String uuid, String code) {
        Captcha captcha = new Captcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        captcha.setCreateTime(LocalDateTime.now());
        captcha.setExpireTime(LocalDateTime.now().plusMinutes(5));
        captchaRepository.save(captcha);
    }

    @Override
    public String getCaptchaCode(String uuid) {
        return captchaRepository.findById(uuid)
                .filter(captcha -> captcha.getExpireTime().isAfter(LocalDateTime.now()))
                .map(Captcha::getCode)
                .orElse(null);
    }

    @Override
    @Transactional
    public void deleteCaptchaCode(String uuid) {
        captchaRepository.deleteById(uuid);
    }

    @Override
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次清理
    @Transactional
    public void cleanExpiredCaptchas() {
        captchaRepository.deleteExpiredCaptchas(LocalDateTime.now());
    }

    @Override
    public Map<String, Object> createCaptcha() {
        // Generate captcha text
        String captchaText = captchaProducer.createText();
        
        // Generate captcha image
        BufferedImage image = captchaProducer.createImage(captchaText);
        
        // Convert image to Base64
        String base64Image;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            base64Image = Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            throw new RuntimeException("Failed to generate captcha image", e);
        }
        
        // Generate UUID for the captcha
        String uuid = UUID.randomUUID().toString();
        
        // Store in database
        setCaptchaCode(uuid, captchaText);
        
        // Return result as Map
        Map<String, Object> result = new HashMap<>();
        result.put("uuid", uuid);
        result.put("img", base64Image);
        return result;
    }

    @Override
    public boolean validateCaptcha(String uuid, String code) {
        if (!StringUtils.hasText(uuid) || !StringUtils.hasText(code)) {
            return false;
        }
        
        // Get stored captcha from database
        String storedCode = getCaptchaCode(uuid);
        
        // Delete the captcha from database
        deleteCaptchaCode(uuid);
        
        // Validate the captcha
        return CaptchaUtils.validateCaptcha(code, storedCode);
    }
} 